package middleware

import (
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"shopping-mall/pkg"
	"shopping-mall/shoppingapi/internal/types"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation

		// Passthrough to next handler if need
		token := r.Header.Get("token")
		if token == "" {
			resp := types.Response{
				Message: "当前token没登录",
				Code:    "500",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		err, claims := pkg.GetTokenData(token)
		if err != "" {
			resp := types.Response{
				Message: err,
				Code:    "500",
				Data:    nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		id := claims["id"]
		r.ParseForm()
		r.Form.Set("id", id.(string))
		next(w, r)
	}
}
